import requests
from faker import Faker

# 该session对象可以帮助我们自动管理和传递cookie
# 后续的接口调用都必须使用session对象发起
session = requests.session()
fk = Faker(locale="zh_CN")


def user_login(username='admin', password='admin'):
    url = 'http://192.168.239.129:8080/kejiyinhangyewuguanli/users/login'
    # 以表单参数方式
    data = {
        "username": username,
        "password": password,
    }
    # 发起调用
    resp = session.request(method='post', url=url, data=data)
    # 获取响应状态码
    status_code = resp.status_code
    print(f"响应状态码是:{status_code}")
    # 如果响应数据本身是一个json形式的数据，那么还可以以json格式获取
    resp_json = resp.json()  # 得到的结果有可能是字典也有可能是列表
    print(f'响应数据json形式是:{resp_json}')
    # 提取响应结果中的access_token
    global token
    token = resp_json['token']
    return resp


def add_user(sexTypes=1, zhuxiaoTypes=1, token=""):
    url = 'http://192.168.239.129:8080/kejiyinhangyewuguanli/yonghu/save'
    headers = {
        "Token": token,
        "Content-type": "application/json"
    }

    username = fk.user_name()
    yonghuName = fk.name()
    yonghuPhone = fk.phone_number()
    yonghuIdNumber = fk.ssn()
    yonghuEmail = fk.email()
    yonghuPhoto = f"http://localhost:8080/kejiyinhangyewuguanli/upload/{fk.uuid4()}.jpg"

    payload = {
        "username": username,
        "yonghuUuidNumber": fk.random_number(digits=12),
        "yonghuName": yonghuName,
        "yonghuPhone": yonghuPhone,
        "yonghuIdNumber": yonghuIdNumber,
        "yonghuPhoto": yonghuPhoto,
        "sexTypes": sexTypes,
        "zhuxiaoTypes": zhuxiaoTypes,
        "yonghuEmail": yonghuEmail
    }

    resp = session.post(url=url, headers=headers, json=payload)
    return resp, payload


if __name__ == '__main__':
    user_login()
    # print(add_user(token))

